﻿using DFGK.WMS.Common.Result;
using DFGK.WMS.Common.ValidateRules;
using DFGK_WMS.Model.DTO;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Reflection;

namespace DFGJ.WMS_PDA.WebAPI.Utility.Filters
{
    public class ValidateParaFilterAttribute : Attribute, IAsyncActionFilter
    {
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            List<object>? parameterList =
                    context.ActionArguments.Where(it => it.Value is BaseDto && it.Value is not null)
                   .Select(it => it.Value)
                   .ToList();

            List<(bool, string?)> messageList = new List<(bool, string?)>();  
            foreach (var parameter in parameterList)
            {

                foreach (var value in parameter.GetType().GetProperties())
                {
                    if (value.IsDefined(typeof(BaseAbstractAttribute), true))
                    {
                        BaseAbstractAttribute? action = value.GetCustomAttribute<BaseAbstractAttribute>();

                        messageList.Add(action.DoValidate(value.GetValue(parameter)));   

                    }
                }

            }

            if (messageList.Any(it => it.Item1 == false)) 
            {

                context.Result = new JsonResult(new ApiBaseResult
                {
                     Success=false, 
                     Message=string.Join(",",messageList.Where(it=>it.Item1 == false).Select(it=>it.Item2))
                });
            
            }  
            else 
            {
                await next.Invoke();   
            }



          
        }
    }
}
